/**
 * Copyright phonemap.com
 *
 * Licensed under the phonemap.com License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.phonemap.com/licenses/LICENSE-1.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonemap;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.GeoPt;
import com.phonemap.common.Util;
import com.phonemap.dto.PositionDTO;
import com.phonemap.models.Position;

/**
 * The Class PositionServlet.
 * 
 * @author Administrator
 */
@SuppressWarnings("serial")
public class PositionServlet extends BaseServlet {

	/** The Constant logger. */
	private static Logger logger = Logger.getLogger(PositionServlet.class
			.getCanonicalName());

	/**
	 * Get the requested position entities in JSON format.
	 * 
	 * @param req
	 *            the req
	 * @param resp
	 *            the resp
	 * @throws ServletException
	 *             the servlet exception
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	protected final void doGet(final HttpServletRequest req,
			final HttpServletResponse resp) throws ServletException,
			IOException {

		super.doGet(req, resp);
		logger.log(Level.INFO, "Obtaining Position listing");
		String searchFor = req.getParameter("q");
		PrintWriter out = resp.getWriter();
		Iterable<Entity> entities = null;
		if (searchFor == null || searchFor.equals("")) {
			entities = Position.getAllPositions();
			out.println(Util.writeJSON(entities));
		} else {
			List<PositionDTO> list = Position.getHistory(Long.parseLong(searchFor), 5, 0);
			out.println(Util.writePositionJSON(list));
//			entities = Position.getPositions(Long.parseLong(searchFor));
//			out.println(Util.writeJSON(entities));
		}
		return;
	}

	/**
	 * Insert the new position.
	 * 
	 * @param req
	 *            the req
	 * @param resp
	 *            the resp
	 * @throws ServletException
	 *             the servlet exception
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	protected final void doPut(final HttpServletRequest req,
			final HttpServletResponse resp) throws ServletException,
			IOException {
		logger.log(Level.INFO, "Creating Position");
		String userId = req.getParameter("user");
		float latitude = Float.parseFloat(req.getParameter("latitude"));
		float longitude = Float.parseFloat(req.getParameter("longitude"));
		Position.insertPosition(Long.parseLong(userId), new GeoPt(latitude,
				longitude), new Date());
	}

	/**
	 * Insert the new position.
	 * 
	 * @param req
	 *            the req
	 * @param resp
	 *            the resp
	 * @throws ServletException
	 *             the servlet exception
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	protected final void doDelete(final HttpServletRequest req,
			final HttpServletResponse resp) throws ServletException,
			IOException {
		logger.log(Level.INFO, "Deleting order from the listing");
		String positionId = req.getParameter("id");
		String userId = req.getParameter("parentid");
		if (positionId != null && !positionId.isEmpty()) {
			Position.deletePosition(Long.parseLong(positionId),
					Long.parseLong(userId));
		}

	}

	/**
	 * Redirect the call to doDelete or doPut method.
	 * 
	 * @param req
	 *            the req
	 * @param resp
	 *            the resp
	 * @throws ServletException
	 *             the servlet exception
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	protected final void doPost(final HttpServletRequest req,
			final HttpServletResponse resp) throws ServletException,
			IOException {
		String action = req.getParameter("action");
		if (action.equalsIgnoreCase("delete")) {
			doDelete(req, resp);
			return;
		} else if (action.equalsIgnoreCase("put")) {
			doPut(req, resp);
			return;
		}
	}
}
